import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 09 - 09
 * Time: 18:35
 */
//牛客 括号生成
public class Solution4 {
    int left, right, n;
    StringBuilder path;
    ArrayList<String> ret;
    public ArrayList<String> generateParenthesis (int _n) {
        n = _n;
        path = new StringBuilder();
        ret = new ArrayList<>();
        dfs();
        return ret;
    }
    public void dfs() {
        if(right == n) {
            ret.add(new String(path.toString()));
            return;
        }
        if(left < n) {
            path.append('('); left++;
            dfs();
            path.deleteCharAt(path.length() - 1); left--;
        }
        if(right < left) {
            path.append(')'); right++;
            dfs();
            path.deleteCharAt(path.length() - 1); right--;
        }
    }
}
